package com.leesche.zcsp.node.web.controller.web.user;

import com.alibaba.fastjson.JSON;
import com.leesche.zcsp.node.utils.web.PagingResult;
import com.leesche.zcsp.node.utils.web.messge.WebResult;
import com.leesche.zcsp.node.web.controller.template.UserTemplate;
import com.leesche.zcsp.node.web.model.SysRole;
import com.leesche.zcsp.node.web.model.SysRoleModule;
import com.leesche.zcsp.node.web.model.SysRoleModuleCriteria;
import com.leesche.zcsp.node.web.model.SysUserRoleCriteria;
import com.leesche.zcsp.node.web.service.SysRoleModuleService;
import com.leesche.zcsp.node.web.service.impl.data.read.QuerySysRoleCondition;
import com.leesche.zcsp.node.web.service.impl.data.read.SysRoleDto;
import com.leesche.zcsp.node.web.vo.v2.Menu;
import com.leesche.zcsp.node.web.vo.RoleModule;
import com.leesche.zcsp.node.web.vo.UserGroup;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Title: RoleController.java
 * @Description: TODO(角色控制器)
 * @author 陈立勇
 * @date 2016年9月13日 下午4:06:36
 * @version V1.0
 */
@Controller
@RequestMapping(value = "/web/userGroup")
public class RoleController extends UserTemplate {

	private final static Logger LOGGER = Logger.getLogger(RoleController.class
			.getName());

	private static final String LIST_VIEW = "web/userGroup/listView";
	private static final String ADD_VIEW = "web/userGroup/addView";
	private static final String EDIT_VIEW = "web/userGroup/editView";
	private static final String SETUP_VIEW = "web/userGroup/setupRoleModuleView";


	@Autowired
	private SysRoleModuleService sysRoleModuleService;

	/**
	 *
	 * @Title: showListView
	 * @Description: TODO(获取系统角色列表界面)
	 * @author Jerry Chen
	 * @date 2016年10月2日 下午6:22:05
	 * @return 系统角色列表界面
	 */
	@RequestMapping(value = "/userGrouplist", method = RequestMethod.GET)
	public String showListView() {
		return LIST_VIEW;
	}

	/**
	 *
	 * @Title: showAddView
	 * @Description: TODO(获取系统角色新增界面)
	 * @author Jerry Chen
	 * @date 2016年10月2日 下午6:20:52
	 * @return 系统角色新增界面
	 */
	@RequestMapping(value = "/userGroupAddView", method = RequestMethod.GET)
	public String showAddView() {
		return ADD_VIEW;
	}

	/**
	 *
	 * @Title: showBusineesRole
	 * @Description: TODO(获取系统默认分配且当前在用商业用户类型)
	 * @author Jerry Chen
	 * @date 2016年10月12日 下午3:21:35
	 */
	@ResponseBody
	@RequestMapping(value = "/parentUserGroup.json", method = RequestMethod.GET)
	public List<UserGroup> showBusineesRole() {

		List<UserGroup> ugs = new ArrayList<UserGroup>();
		for (SysRole sysRole : sysRoleService.findSysRoleParentTree()) {
			UserGroup ug = new UserGroup();
			ug.setUserGroupid(sysRole.getRoleid());
			ug.setTextCN(sysRole.getNamecn());
			ug.setTextEN(sysRole.getSname());
			ug.setRemark(sysRole.getRemark());
			ugs.add(ug);
		}

		return ugs;
	}

	/**
	 *
	 * @Title: showEditView
	 * @Description: TODO(获取系统角色编辑界面)
	 * @author Jerry Chen
	 * @date 2016年10月2日 下午6:19:30
	 * @param id
	 *            被编辑的角色ID
	 * @param model
	 * @return 包含系统角色信息的编辑界面
	 */
	@RequestMapping(value = "/{id}/userGroupEditView", method = RequestMethod.GET)
	public String showEditView(final @PathVariable("id") Long id,
							   final Model model) {

		SysRole sysRole = sysRoleService.selectByPrimaryKey(id);

		UserGroup ug = new UserGroup();
		ug.setUserGroupid(sysRole.getRoleid());
		ug.setParentid(sysRole.getProleid());
		ug.setTextCN(sysRole.getNamecn());
		ug.setTextEN(sysRole.getSname());
		ug.setRemark(sysRole.getRemark());
		ug.setIsDefault(sysRole.getIsdefault());
		ug.setIsShare(sysRole.getIsshare());
		ug.setUseState(sysRole.getState());
		ug.setUserGroupType(sysRole.getNtype());

		model.addAttribute("usergroup", ug);

		return EDIT_VIEW;
	}

	/**
	 *
	 * @Title: showSetupView
	 * @Description: TODO(获取系统角色列表界面)
	 * @author Jerry Chen
	 * @date 2016年10月2日 下午6:22:05
	 * @return 系统角色列表界面
	 */
	@RequestMapping(value = "/{id}/setupModuleView", method = RequestMethod.GET)
	public String showSetupView(final @PathVariable("id") Long id,Model model) {

		SysRole sysRole = sysRoleService.selectByPrimaryKey(id);
		List<SysRoleModule> sysRoleModules = sysRoleModuleService.findRoleModuleByRoleid(id);

		List<Long> moduleid = new ArrayList<Long>();
		for (SysRoleModule roleModule : sysRoleModules) {
			moduleid.add(roleModule.getModuleid());
		}

		/*Map<Integer, List<Menu>> modules = (Map<Integer, List<Menu>>) SessionManager.getSessionAttribute("setupRoleModules");
		if(modules == null){
			modules = sysModuleService.findAllSysModules();
			SessionManager.setSessionAttribute("setupRoleModules", modules);
		}*/

		model.addAttribute("usergroup", sysRole);
		model.addAttribute("sysRoleModules", JSON.toJSONString(moduleid));

		return SETUP_VIEW;
	}

	/**
	 * @return 响应报文
	 * @Title: listJson
	 * @Description: TODO(获取系统角色分页信息)
	 * @author 陈立勇
	 */
	@ResponseBody
	@RequestMapping(value = "/module.json", method = RequestMethod.GET)
	public Map<Integer, List<Menu>> moduleJson() {

		Map<Integer, List<Menu>> menus = sysModuleService.findAllSysModules();

		for (Integer integer : menus.keySet()) {
			List<Menu> m =menus.get(integer);
			for (Menu menu : m) {
				System.out.println(menu.getText());
			}
		}

		return menus;
	}

	/**
	 * @param condition
	 *            分页条件
	 * @return 响应报文
	 * @Title: listJson
	 * @Description: TODO(获取系统角色分页信息)
	 * @author 陈立勇
	 */
	@ResponseBody
	@RequestMapping(value = "/list.json", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	public Map<String, Object> listJson(final QuerySysRoleCondition condition) {

		PagingResult<SysRoleDto> pagingResult = getSysRoleDtoPagingResult(condition);

		Map<String, Object> json = WebResult.buildOf(pagingResult).toMap();

		return json;
	}


	/**
	 * @param role
	 *            需新增的角色信息
	 * @Title: addRole
	 * @Description: TODO(新增系统角色)
	 * @author 陈立勇
	 */
	@ResponseBody
	@RequestMapping(value = "/newUserGroup", method = RequestMethod.POST)
	public Map<String, Object> addRole(final SysRole role) {
		try {
			// 获取当前登录的用户
			role.setAdminid(privilegeService.getCurrentPrincipal().getUserid());
			role.setUpdatetime(new Date());

			if (role.getProleid() == null || role.getProleid() == 0) {
				role.setProleid(1L);
			}

			if (role.getNtype() != 1) {
				role.setNtype(sysRoleService.countRoleTotal() + 1);
			}

			sysRoleService.insertSelective(role);
			return WebResult.success().info("操作成功！").toMap();

		} catch (Exception e) {
			LOGGER.error(e, e);
			return WebResult.failure(e).toMap();
		}

	}

	/**
	 * @param role
	 *            需编辑的系统角色信息
	 * @Title: editRole
	 * @Description: TODO(编辑系统角色)
	 * @author 陈立勇
	 */
	@ResponseBody
	@RequestMapping(value = "/eidtUserGroup", method = RequestMethod.POST)
	public Map<String, Object> editRole(final SysRole role) {
		try {
			// 获取当前登录的用户
			role.setAdminid(privilegeService.getCurrentPrincipal().getUserid());
			role.setUpdatetime(new Date());

			sysRoleService.updateByPrimaryKeySelective(role);
			return WebResult.success().info("操作成功！").toMap();
		} catch (Exception e) {
			LOGGER.error(e, e);
			return WebResult.failure(e).toMap();
		}

	}

	/**
	 * @param id
	 *            需删除的角色ID
	 * @Title: delRole
	 * @Description: TODO(移除系统角色)
	 * @author 陈立勇
	 */
	@ResponseBody
	@RequestMapping(value = "/{id}/removeUserGroup", method = RequestMethod.DELETE)
	public Map<String, Object> delRole(final @PathVariable("id") long id) {
		try {
			// 删除用户角色
			SysUserRoleCriteria urCriteria = new SysUserRoleCriteria();
			urCriteria.or().andRoleidEqualTo(id);
			sysUserRoleService.deleteByCriteria(urCriteria);
			// 删除角色权限
			SysRoleModuleCriteria rmCriteria = new SysRoleModuleCriteria();
			rmCriteria.or().andRoleidEqualTo(id);
			sysRoleModuleService.deleteByCriteria(rmCriteria);
			// 删除角色
			sysRoleService.deleteByPrimaryKey(id);
			return WebResult.success().info("操作成功！").toMap();
		} catch (Exception e) {
			LOGGER.error(e, e);
			return WebResult.failure(e).toMap();
		}

	}

	/**
	 *
	 * @Title: activeRoleModule
	 * @Description: TODO(设置角色权限)
	 * @author Jerry Chen
	 * @date 2016年10月3日 下午3:31:32
	 */
	@ResponseBody
	@RequestMapping(value = "/setupRoleModule", method = RequestMethod.POST)
	public Map<String, Object> setupRoleModule(final RoleModule rm) {

		try {

			Long roleID = rm.getRoleid();
			/* 设置角色的权限之前，先清空掉原来已经设置好的权限 */
			SysRoleModuleCriteria criteria = new SysRoleModuleCriteria();
			criteria.or().andRoleidEqualTo(roleID);
			sysRoleModuleService.deleteByCriteria(criteria);

			Long adminid = 1L;
			Date updatetime = new Date();

			List<SysRoleModule> sysRoleModules = new ArrayList<SysRoleModule>();
			for (Long moduleid : rm.getModuleid()) {
				SysRoleModule sysRoleModule = new SysRoleModule();
				sysRoleModule.setAdminid(adminid);
				sysRoleModule.setUpdatetime(updatetime);
				sysRoleModule.setModuleid(moduleid);
				sysRoleModule.setRoleid(roleID);
				sysRoleModules.add(sysRoleModule);
			}

			sysRoleModuleService.setupRoleModule(sysRoleModules);

			return WebResult.success().info("操作成功！").toMap();

		} catch (Exception e) {
			// TODO: handle exception
			LOGGER.error(e, e);
			return WebResult.failure(e).toMap();
		}

	}

}
